<template>
    <div class="submitorder">
       <v-header title="确认订单" ref="header" @back="handleNativeBack" :handleClick='true'></v-header>
       <div>
           <scroll ref="scroll" style="overflow: hidden;height: 100%"
           :style="{height: scrollHeight + 'px'}">
               <div>
                   <cell-box is-link class="addressWrapper" @click.native="handleGoAddressmanage">
                        <div v-if="adressManager">
                            <div class="addressPerson">
                                <span class="firstSpan">{{address.receiptName}}</span>
                                <span class="secondSpan">{{address.receiptPhone}}</span>
                                <button>默认</button>
                            </div>
                            <div class="addressDetail">
                                <i class="fa fa-map-marker" aria-hidden="true"></i>
                                <span>{{address.receiptProvince + address.receiptCity + address.receiptArea + address.detailAddress}}</span>
                            </div>
                        </div>
                        <div v-else class="noAddress">
                            <img :src="superiseImage" alt="">
                            <p>还未添加默认收获地址，立即去添加</p>
                        </div>
                   </cell-box>

                   <!-- 线条 -->
                   <div class="lineWraopper">
                   </div>
                   <!-- 商品展示 -->
                   <cell-box class="shoppingShow" is-link @click.native="handleShoppingList">
                       <div class="shoppingShowContent">
                            <div>
                                <img :src="item.thumbUrl" alt="" class="shoppingImage" v-for="(item, index) in shoppingList" v-if="index < 4" :key="item.id">
                            </div>
                        </div>
                   </cell-box>

                    <div class="shoppingAll">
                        <p>共{{shoppingList.length}}种商品类型 共{{shoppingCount}}件商品</p>
                    </div>
                  <!-- 支付配送 -->
                    <div class="payStyle">
                        <div class="payDistribution">
                            <div class="pay">
                                <p>支付配送</p>
                            </div>
                            <div class="payDesc">
                                <div>
                                    <div>
                                        <p>在线支付</p>
                                    </div>
                                    <div>
                                        <p>快递运输</p>
                                    </div>
                                    <div>
                                        <p>
                                            <i class="fa fa-clock-o" aria-hidden="true" style="color: red"></i> 工作日、双休日与节假日均可送货
                                        </p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 发票 -->
                    <div class="invoice" @click="handleOpenInvoice">
                        <cell title="发票" is-link v-model="invoiceValue" inline-desc="选择电子发票，免邮费"></cell>
                    </div>

                    <!-- 商品金额 -->
                    <div class="shoppingMoney">
                        <div class="shoppingMoneyWrapper">
                            <p>商品金额</p>
                            <p class="shoppingpricecalc">¥ {{totalMoney}}</p>
                        </div>
                        <div class="shoppingSub">
                            <p>立减</p>
                            <p class="shoppingpricecalc">- ¥ {{preferentialPriceCalc}}</p>
                        </div>
                        <div class="shoppingFreight">
                            <p>运费</p>
                            <p class="shoppingpricecalc">+ ¥0.00</p>
                        </div>
                    </div>

                    <!-- 备注、给商家留言 -->
                    <div class="leaveMessage">
                        <x-textarea placeholder="备注、给商家留言(60字以内)" :show-counter="false" :rows="1" autosize v-model="leaveMessage" :max="60" title="备注">
                        </x-textarea>
                    </div>
                </div>
           </scroll>
       </div>
       <!-- 底部购物车菜单 -->
       <div class="bottomDiv" ref="bottomWrapper">
            <div class="bottomDivLeft">
                <p>实付款：<span>¥ {{allMoney}}</span></p>
            </div>
            <div class="bottomDivRight" @click="submitOrder">
                <p>
                    提交订单
                </p>
            </div>
       </div>
    </div>
</template>

<script>
import VHeader from '@/components/v-header/v-header'
import axios from '@/api/axiosApi'
import Scroll from '@/components/scroll/scroll'
import { localUser } from '@/assets/js/local'
import { handleBackMixin } from '@/assets/js/mixin'
import superiseImage from '@/assets/img/myhome/superise.png'
import { mapGetters } from 'vuex'
import { CellBox, Cell, XTextarea, Actionsheet } from 'vux'
export default {
  mixins: [handleBackMixin],
  data () {
    return {
      superiseImage: superiseImage,
      scrollHeight: '500px',
      imgUrl: 'http://p0w4yb0aj.bkt.clouddn.com/background_my.jpg',
      address: {},
      addressList: [],
      invoiceValue: '未申请',
      invoiceFlag: 0,
      leaveMessage: '',
      shoppingCount: 0,
      adressManager: true,
      allShoppingList: [],
      allPopupModels: []
    }
  },
  mounted () {
    this.scrollHeight = window.innerHeight - this.$refs.header.$el.offsetHeight - 60
  },
  created () {
    this.getAddressAndInfo()
    // 获取所有购物车数据
    this.handleGetShopping()
    // 作路由判断发票是否已经申请
    if (this.$route.query.isSubmitInvoice) {
      if (this.$route.query.isSubmitInvoice === '1' || this.$route.query.isSubmitInvoice === 1) {
        this.invoiceValue = '已申请'
      } else {
        this.invoiceValue = '未申请'
      }
    }
    this.shoppingCount = sessionStorage.getItem('shoppingCount')
  },
  computed: {
    ...mapGetters([
      'shoppingList',
      'invoice'
    ]),
    // 计算计划付款
    totalMoney () {
      let countMoney = 0
      this.shoppingList.forEach(item => {
        countMoney += item.goodsNum * item.normalPrice
      })
      return countMoney.toFixed(2)
    },
    // 计算优惠价格
    preferentialPriceCalc () {
      let preferentialPrice = 0
      this.shoppingList.forEach(item => {
        if (item.discount === 0 || undefined === item.discount) {
          preferentialPrice += 0
        } else {
          preferentialPrice += (item.normalPrice - item.discountPrice) * item.goodsNum
        }
      })
      return preferentialPrice.toFixed(2)
    },
    // 计算实付款
    allMoney () {
      let allMoneyNum = 0
      this.shoppingList.forEach(item => {
        if (item.discount === 0 || undefined === item.discount) {
          allMoneyNum += item.goodsNum * item.normalPrice
        } else {
          allMoneyNum += item.goodsNum * item.discountPrice
        }
      })
      return allMoneyNum.toFixed(2)
    }
  },
  methods: {
    // 得到默认地址和个人信息
    getAddressAndInfo () {
      axios.get(this, '/v1/receiptAddress', {userId: localUser.get('id'), defaultAddress: 1}, (data) => {
        this.addressList = data
        if (this.addressList.length > 0) {
          this.address = this.addressList[0]
        } else {
          this.adressManager = false
        }
      })
    },
    submitOrder () {
      const _self = this
      if (this.addressList.length === 0) {
        this.$vux.toast.text('未添加收获地址额', 'middle')
        return
      }
      // 计算特产的数量
      let countNum = 0
      this.shoppingList.forEach(item => {
        countNum += item.goodsNum
      })
      // 判断是否需要发票
      if (this.invoiceValue === '已申请') {
        this.invoiceFlag = 1
      } else {
        this.invoiceFlag = 0
      }
      // 拼接参数
      let param = {
        goodsName: this.shoppingList[0].goodsName + '等' + countNum + '件特产',
        goodsDesc: this.shoppingList[0].goodsIntro,
        buyerId: localUser.get('id'),
        receiptAddress: this.address.receiptProvince + this.address.receiptCity + this.address.receiptArea + this.address.detailAddress,
        // 发票信息
        invoice: this.invoiceFlag,
        invoiceType: this.invoice.invoiceType,
        invoiceRiseType: this.invoice.invoiceRiseType,
        invoiceContentType: this.invoice.invoiceContentType,
        companyName: this.invoice.companyName,
        registrationNumber: this.invoice.registrationNumber,
        accountPhone: this.invoice.accountPhone,
        accountEmail: this.invoice.accountEmail,

        phone: this.address.receiptPhone,
        concat: this.address.receiptName,
        orderGoodsList: this.shoppingList,
        remark: this.leaveMessage
      }
      axios.put(this, '/v1/order/', {orderString: JSON.stringify(param)}, (res) => {
        // 结算时候删除已经选择的订单
        let ids = sessionStorage.getItem('selectedIds')
        let idsTemp = []
        idsTemp = ids.split(',')
        axios.delete(_self, '/v1/shoppingCart/' + idsTemp.toString(), null, (data) => {
          idsTemp.forEach(i => {
            const idx = _self.allShoppingList.findIndex(o => o.id === i)
            if (idx > -1) {
              _self.allShoppingList.splice(idx, 1)
            }
          })
        })
        this.$vux.toast.text('订单提交成功！', 'middle')
        _self.$router.push(`/orderList?type=201`)
      })
    },
    handleGoAddressmanage () {
      this.$router.push('/user/harvestaddress')
    },
    handleShoppingList () {
      this.$router.push('/user/shoppinglist')
    },
    handleOpenInvoice () {
      this.$router.push('/user/openinvoice')
    },
    // 获取我的购物车所有数据
    handleGetShopping () {
      axios.get(this, '/v1/shoppingCart/' + localUser.get('id'), null, (data) => {
        this.allShoppingList = data
      })
    },
    // 对订单返回进行处理，android这里返回也需要做判断
    handleNativeBack () {
      const _self = this
      _self.$vux.confirm.show({
        title: '温馨提示',
        content: '你忍心丢下已经选好的宝贝吗',
        onConfirm () {
          _self.$router.go(-1)
        }
      })
      return true
    }
  },
  components: {
    VHeader,
    axios,
    localUser,
    Scroll,
    CellBox,
    Cell,
    XTextarea,
    Actionsheet
  }
}
</script>

<style lang="stylus" scoped>
@import '~@/assets/css/variable.styl'
.submitorder {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: $color-background;
  z-index: 101;
  height:100%;
}

.addressWrapper {
    background-color white
    .addressPerson {
        padding-left 15px
        padding-right 15px
        span {
            font-weight bold
        }
        .secondSpan {
            margin-left 20px
        }
        button {
            margin-left 5px
            color: red;
            width: 37px;
            height: 19px;
            border: solid 1px red;
            border-radius 3px
            background-color: #fff;
            &:focus {
            outline: none
            }
        }
    }

    .noAddress {
        display flex
        img {
            width: 30px
            height 31px
            background-size: cover
            background-repeat: no-repeat
        }
        p {
            margin-left 10px
        }
    }

    .addressDetail {
        padding-top 10px
        padding-left 15px
        padding-right 15px
        padding-bottom 8px
        span {
            font-size $font-size-desc
        }
        color $color-text-2
    }
}

.shoppingShow {
    margin-top 10px
    background-color white
    padding-top 15px
    padding-left 10px
    padding-right 15px
    padding-bottom 5px
    .shoppingShowContent {
        width 96%
        justify-content space-between
    }
    .shoppingImage {
        margin-left 5px
        width: 60px
        height 61px
        background-size: cover
        background-repeat: no-repeat
    }
}

.shoppingAll {
    background-color white
    text-align right
    adding-top 0px
    padding-left 10px
    padding-right 15px
    padding-bottom 10px
}

.payStyle {
    border-top-style solid
    border-width:1px
    border-color: #E4E4E4
    background-color white
    padding-top 10px
    padding-left 10px
    padding-right 15px
    padding-bottom 10px
    .payDistribution {
        display flex
        justify-content space-between
        .payDesc {
            display flex
            align-items center
            text-align right
        }
    }
    .payDisDetail {
        margin-left 5px
    }
}


.lineWraopper {
    background: -webkit-linear-gradient(left,#248BBA,white,#E08349,white,#D96083,white,#248BBA,white,#E08349,white,#D96083,white,#248BBA,white,#E08349,white,#D96083,white,#248BBA,white,#E08349,white,#D96083,white,#248BBA,white,#E08349,white,#D96083,white,#248BBA);
    height:2px;
    width: 100%
}

.invoice {
 background-color white
 margin-top 10px
}

.shoppingMoney {
    margin-top 10px
    background-color white
    padding-top 10px
    padding-left 15px
    padding-right 15px
    padding-bottom 10px
    .shoppingpricecalc {
        color red
    }
    .shoppingMoneyWrapper {
        display flex
        justify-content space-between
    }
    .shoppingSub {
        display flex
        justify-content space-between
    }
    .shoppingFreight {
        display flex
        justify-content space-between
    }
}

.leaveMessage {
    margin-top 10px
    background-color white
}

.bottomDiv {
  z-index 999
  background-color white
  display flex
  width 100%
  height 60px
  position absolute
  bottom 0px
  .bottomDivLeft {
    margin-top 20px
    margin-right 30px
    text-align right
    width 60%
    height 60px
    p {
        span {
            color red
        }
    }
  }
  .bottomDivRight {
    line-height 60px
    text-align center
    width 40%
    height 60px
    background-color red
    p {
        color white
        font-size $font-size-large
    }
  }
}
</style>

